#include <REGX52.H>
#include <intrins.h>
#include <string.h>

#define SIZE 26

char buffer[SIZE];

sfr AUXR = 0x8e;
sbit D5 = P3^7;
sbit D6 = P3^6;
		


//1 工作在路由模式
char LYMO[] = "AT+CWMODE=2\r\n";
//2 使能多链接
char DLJ[] = "AT+CIPMUX=1\r\n";
//3 建立TCPServer
char JLFW[] = "AT+CIPSERVER=1\r\n"; // default port = 333
//发送数据
char FSSJ[] = "AT+CIPSEND=0,5\r\n"; 

char AT_OK_Flag = 0; //OK返回值的标志位
char AT_Connect_Net_Flag = 0; //WIFI GOT IP返回值的标志位
char Client_Connect_Flag = 0;


void Delay1000ms()		//@11.0592MHz
{
	unsigned char i, j, k;

	_nop_();
	i = 8;
	j = 1;
	k = 243;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}


void InitUart(){

	AUXR  = 0x01;
	SCON  = 0x50;
	TMOD &= 0xF0;
	TMOD |= 0x20;
	
	TH1   = 0xFD;
	TL1   = 0xFD;
	TR1   = 1;
	
	EA    = 1;
	ES    = 1;

}

void SendByte(char data_masg){
	
	SBUF = data_masg;
	while(!TI);
	TI = 0;
}

void sendString(char* str){

	while( *str != '\0'){
		
		SendByte(*str);
		str++;
	}
}

int main(){
	
	D5 = D6 =1;
	InitUart();
	Delay1000ms();
	Delay1000ms();	//等待上电
	
	
	sendString(LYMO);
	while(!AT_OK_Flag);
	AT_OK_Flag = 0;
	
	sendString(DLJ);
	while(!AT_OK_Flag);
	AT_OK_Flag = 0;
	
	sendString(JLFW);
	while(!Client_Connect_Flag);
	AT_OK_Flag = 0;
	
	if(Client_Connect_Flag){
		D5 = 0;//点亮D5,代表有客户端接入
		D6 = 0;
	}
		
	//心跳包
	while(1){
		//4 发送数据
		sendString(FSSJ);
		Delay1000ms();
		Delay1000ms();
		sendString("Hello");
		Delay1000ms();
		Delay1000ms();
	}
}

void Uart_Handler() interrupt 4
{	
	char tmp = 0;
	static int i = 0;
	
	if(RI)//中断处理函数中，对于接收中断的响应
	{
		
		RI = 0;//清除接收中断标志位
		tmp = SBUF;//临时变量接收第一位数据
		
		//位置预设，将传进来的相关数据置位为第0位
		if(tmp == 'O' || tmp == 'L' || tmp == '0' || tmp == 'W'){
			i = 0;
		}
		buffer[i++] = tmp;
		
		if(buffer[0] == 'W' && buffer[5] == 'G'){
			AT_Connect_Net_Flag = 1;
			memset(buffer, '\0', SIZE);
		}
		//连接服务器等OK返回值指令的判断
		if(buffer[0] == 'O' && buffer[1] == 'K'){
			AT_OK_Flag = 1;
			memset(buffer, '\0', SIZE);
		}
		if(buffer[0] == '0' && buffer[2] == 'C'){
			Client_Connect_Flag = 1;
			memset(buffer, '\0', SIZE);
		}
		
		if(buffer[0] == 'L' && buffer[2] == '1' ){
			D5 = 0;//点亮D5
			memset(buffer, '\0', SIZE);
		}
		if(buffer[0] == 'L' && buffer[2] == '0'){
			D5 = 1;//熄灭D5
			memset(buffer, '\0', SIZE);
		}
		if(i == SIZE) 
		{i = 0;}
	}
	
}